<?php

CCore::Using('mime.part');
CCore::Using('mime.utils');
CCore::Using('mime.callbacks.interface');

class CCoreMimeCallbacksTest implements ICoreMimeCallbacks
{

	private $_iAttachToDownload = 2;
	private $_iAttachmentCount = 0;
	private $_sEndBuffer = '';
	private $_sFunctionName = '';

	/**
	 * @var CCoreMimePart
	 */
	private $_oCurrentMime = null;


	/**
	 * @param CCoreMimePart $oMimePart
	 * @return void
	 */
	public function StartParse(CCoreMimePart &$oMimePart) {}

	/**
	 * @param CCoreMimePart $oMimePart
	 * @return void
	 */
	public function EndParse(CCoreMimePart &$oMimePart) {}

	/**
	 * @param CCoreMimePart $oMimePart
	 * @return void
	 */
	public function StartParseMimePart(CCoreMimePart &$oMimePart)
	{
		$this->_oCurrentMime =& $oMimePart;
	}

	/**
	 * @param CCoreMimePart $oMimePart
	 * @return void
	 */
	public function EndParseMimePart(CCoreMimePart &$oMimePart)
	{
		if ($this->_iAttachmentCount === $this->_iAttachToDownload)
		{
			$f = $this->_sFunctionName;
			echo CCoreMimeUtils::$f($this->_sEndBuffer, $this->_sEndBuffer);
		}
	}

	/**
	 * @return void
	 */
	public function InitMimePartHeader()
	{
		$sName = $this->_oCurrentMime->Headers->GetParamDecodedValueFromHeader('Content-Disposition', 'filename');
		$this->_iAttachmentCount += (0 < strlen($sName)) ? 1 : 0;

		$sFunctionName = $this->_oCurrentMime->Headers->GetInlineDecodeFunctionName();

		//if (false)
		if (true && $this->_iAttachmentCount === $this->_iAttachToDownload)
		{
			$sContentType = trim($this->_oCurrentMime->Headers->GetContentTypeValue());
			#TODO: добавить определение типа по имени файла
			$sContentType = empty($sContentType) ? 'application/octet-stream' : $sContentType;
			@header('Content-Type: '.$sContentType);
			@header('Content-Disposition: attachment; filename="'.$sName.'"; charset="utf-8";');
		}

		$this->_sFunctionName = $sFunctionName;
	}

	/**
	 * @param string $sBuffer
	 * @return void
	 */
	public function ReadBuffer($sBuffer)
	{
		//echo $sBuffer;
	}

	/**
	 * @param string $sBuffer
	 * @return void
	 */
	public function WriteBody($sBuffer)
	{
		if ($this->_iAttachmentCount === $this->_iAttachToDownload)
		{
			$f = $this->_sFunctionName;
			echo CCoreMimeUtils::$f($this->_sEndBuffer.$sBuffer, $this->_sEndBuffer);
		}
	}
}
